#!/usr/bin/python

from Tkinter import *
import cPickle as pickle
import os


root= Tk()
canvas = Canvas(root, bg="white", height=500, width=1000)

lastx, lasty = 0, 0

tracks = []
track_buffer = []

def update_xy(event):
    global lastx, lasty
    lastx, lasty = event.x, event.y

def create_circle(x,y,r,**args):
    canvas.create_oval( (x-r,y-r,x+r,y+r), args)


def add_line(event):
    global lastx, lasty
    global tracks, track_buffer
    # canvas.create_line( (lastx, lasty, event.x, event.y), width=2.0 )
    # canvas.create_oval( (lastx, lasty, event.x, event.y), width=2.0 )
    # create_circle( event.x, event.y, 3, width=2.0, fill="blue")
    canvas.create_line( (lastx, lasty, event.x, event.y), width=2, fill="blue", tags="buffer")
    # record the point
    tracks.append( (lastx, lasty, event.x, event.y) )

    track_buffer.append( (lastx, lasty, event.x, event.y) )

    lastx, lasty = event.x, event.y

    
def clean():
    global tracks
    canvas.delete(ALL)
    tracks = []
        
def redraw():
    global tracks
    for coords in tracks:
        # canvas.create_rectangle( coords, width=2, fill="red" )
        canvas.create_oval( coords, width=2, fill="red" )
        
def release_mouse(event):
    global track_buffer
    # redraw()
    for id in canvas.find_withtag("buffer"):
        canvas.delete(id)
        
    for coords in track_buffer:
        # canvas.create_oval(coords, fill="red")
        canvas.create_line(coords, width=4, fill="red")
        
    track_buffer = []

def save_draw():
    pickle.dump(tracks, open("save.drw","wb"), True)
    


drawing_step = 0
drawing_stop = False
def draw_step(color="blue"):
    global drawing_step, drawing_stop
    if drawing_stop or drawing_step>=len(tracks):
        drawing_step = 0
        if color=="blue":
            root.after(10, draw_step, "red")
        else:
            root.after(10, draw_step, "blue")
        return;
    canvas.create_oval(tracks[drawing_step], width=2, fill=color)
    drawing_step += 1
    root.after(10, draw_step, color)

    
def test():
    global drawing_step, drawing_stop
    drawing_step = 0
    drawing_stop = False
    canvas.delete(ALL)
    draw_step(color="red")

    
    
canvas.bind("<Button-1>", update_xy)
canvas.bind("<ButtonRelease-1>", release_mouse)
canvas.bind("<B1-Motion>", add_line)

# coord = 10, 50, 240, 210
# arc = canvas.create_arc(coord, start=0, extent=150, fill="red")

canvas.pack()


clean_btn = Button(root, text="clean", command=clean)
redraw_btn = Button(root, text="redraw", command=redraw)
save_btn = Button(root, text="save", command=save_draw)
test_btn = Button(root, text="test", command=test)


clean_btn.pack()
redraw_btn.pack()
save_btn.pack()
test_btn.pack()


# open the last drawing
drawing_file = "save.drw"
if os.path.isfile(drawing_file):
    tracks = pickle.load(open(drawing_file, "rb"))
    redraw()


root.mainloop()
